package com.doubao.wechat.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.doubao.common.result.Result;
import com.doubao.wechat.entity.PaymentOrder;
import com.doubao.wechat.entity.RefundOrder;
import com.doubao.wechat.mapper.PaymentOrderMapper;
import com.doubao.wechat.mapper.RefundOrderMapper;
import com.doubao.wechat.service.RefundService;
import com.doubao.wechat.service.WxPayService;
import com.doubao.wechat.util.OrderNumberUtil;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.List;
import java.util.Map;

/**
 * 退款服务实现类
 */
@Service
@RequiredArgsConstructor
@Slf4j
public class RefundServiceImpl extends ServiceImpl<RefundOrderMapper, RefundOrder> implements RefundService {

    private final RefundOrderMapper refundOrderMapper;
    private final PaymentOrderMapper paymentOrderMapper;
    private final WxPayService wxPayService;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Result<RefundOrder> createRefund(Long userId, String outTradeNo, Integer amount, String reason) {
        try {
            // 查询支付订单
            PaymentOrder paymentOrder = paymentOrderMapper.selectByOutTradeNo(outTradeNo);
            if (paymentOrder == null) {
                return Result.failed("支付订单不存在");
            }

            // 检查用户是否一致
            if (!userId.equals(paymentOrder.getUserId())) {
                return Result.failed("无权操作此订单");
            }

            // 检查订单状态
            if (!"SUCCESS".equals(paymentOrder.getStatus())) {
                return Result.failed("订单状态不允许退款");
            }

            // 检查退款金额
            if (amount <= 0 || amount > paymentOrder.getAmount()) {
                return Result.failed("退款金额无效");
            }

            // 检查是否已申请过退款
            Integer refundedAmount = paymentOrder.getRefundAmount();
            if (refundedAmount >= paymentOrder.getAmount()) {
                return Result.failed("订单已全额退款");
            }

            if (refundedAmount + amount > paymentOrder.getAmount()) {
                return Result.failed("退款金额超过剩余可退金额");
            }

            // 生成商户退款单号
            String outRefundNo = OrderNumberUtil.generateRefundOrderNumber();

            // 创建退款订单
            RefundOrder refundOrder = new RefundOrder();
            refundOrder.setPaymentOrderId(paymentOrder.getId());
            refundOrder.setUserId(userId);
            refundOrder.setOutRefundNo(outRefundNo);
            refundOrder.setOutTradeNo(outTradeNo);
            refundOrder.setTradeNo(paymentOrder.getTradeNo());
            refundOrder.setRefundAmount(amount);
            refundOrder.setRefundReason(reason);
            refundOrder.setStatus("PROCESSING");
            refundOrder.setCreatedAt(LocalDateTime.now());
            refundOrder.setUpdatedAt(LocalDateTime.now());

            // 保存退款订单
            save(refundOrder);

            // 更新支付订单的退款状态
            paymentOrder.setRefundAmount(refundedAmount + amount);
            if (paymentOrder.getRefundAmount().equals(paymentOrder.getAmount())) {
                paymentOrder.setRefundStatus(2); // 全额退款
                paymentOrder.setStatus("REFUNDED");
            } else {
                paymentOrder.setRefundStatus(1); // 部分退款
            }
            paymentOrder.setUpdatedAt(LocalDateTime.now());
            paymentOrderMapper.updateById(paymentOrder);

            // 调用微信支付退款接口
            Result<Map<String, Object>> refundResult = wxPayService.refund(
                    outTradeNo, outRefundNo, amount, reason);

            if (!refundResult.isSuccess()) {
                // 退款申请失败，回滚业务状态
                throw new RuntimeException("调用微信支付退款接口失败：" + refundResult.getMessage());
            }

            return Result.success(refundOrder);
        } catch (Exception e) {
            log.error("创建退款申请异常", e);
            return Result.failed("创建退款申请异常：" + e.getMessage());
        }
    }

    @Override
    public Result<RefundOrder> getRefundByOutRefundNo(String outRefundNo) {
        try {
            RefundOrder refundOrder = refundOrderMapper.selectByOutRefundNo(outRefundNo);
            if (refundOrder == null) {
                return Result.failed("退款单不存在");
            }
            return Result.success(refundOrder);
        } catch (Exception e) {
            log.error("查询退款单异常", e);
            return Result.failed("查询退款单异常：" + e.getMessage());
        }
    }

    @Override
    public Result<List<RefundOrder>> getRefundsByOutTradeNo(String outTradeNo) {
        try {
            LambdaQueryWrapper<RefundOrder> wrapper = new LambdaQueryWrapper<>();
            wrapper.eq(RefundOrder::getOutTradeNo, outTradeNo);
            wrapper.orderByDesc(RefundOrder::getCreatedAt);

            List<RefundOrder> refundList = list(wrapper);
            return Result.success(refundList);
        } catch (Exception e) {
            log.error("查询订单退款记录异常", e);
            return Result.failed("查询订单退款记录异常：" + e.getMessage());
        }
    }

    @Override
    public Result<List<RefundOrder>> getUserRefunds(Long userId) {
        try {
            LambdaQueryWrapper<RefundOrder> wrapper = new LambdaQueryWrapper<>();
            wrapper.eq(RefundOrder::getUserId, userId);
            wrapper.orderByDesc(RefundOrder::getCreatedAt);

            List<RefundOrder> refundList = list(wrapper);
            return Result.success(refundList);
        } catch (Exception e) {
            log.error("查询用户退款记录异常", e);
            return Result.failed("查询用户退款记录异常：" + e.getMessage());
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Result<Void> updateRefundStatus(String outRefundNo, String status, String refundId) {
        try {
            // 查询退款单
            RefundOrder refundOrder = refundOrderMapper.selectByOutRefundNo(outRefundNo);
            if (refundOrder == null) {
                return Result.failed("退款单不存在");
            }

            // 更新退款单状态
            refundOrder.setStatus(status);
            refundOrder.setRefundId(refundId);
            refundOrder.setUpdatedAt(LocalDateTime.now());

            // 如果是退款成功，设置退款时间
            if ("SUCCESS".equals(status)) {
                refundOrder.setRefundTime(LocalDateTime.now());
            }

            // 更新退款单
            updateById(refundOrder);

            return Result.success();
        } catch (Exception e) {
            log.error("更新退款状态异常", e);
            return Result.failed("更新退款状态异常：" + e.getMessage());
        }
    }
}